package puzzle.hashikake.view.swing;

import java.awt.Color;
import java.awt.Graphics2D;

import puzzle.common.point.Direction;
import puzzle.common.point.Pnt;
import puzzle.common.view.swing.AbstractPuzzleViewPanel;
import puzzle.hashikake.data.HashiState;
import puzzle.hashikake.data.HashikakeBoard;
import puzzle.hashikake.data.ShimaDef;
import tomoto.assertion.AssertUtil;

public class HashikakeViewPanel extends AbstractPuzzleViewPanel<HashikakeBoard> {

	private static final long serialVersionUID = 1L;

	@Override
	protected void paintBoard(Graphics2D g2, HashikakeBoard b) {
		int interval = 3;

		// draw hashis
		for (HashiState s : b.getHashiStates()) {
			int x1 = s.def.car.p.x * m_cellSize + m_cellSize / 2;
			int y1 = s.def.car.p.y * m_cellSize + m_cellSize / 2;
			int x2 = s.def.cdr.p.x * m_cellSize + m_cellSize / 2;
			int y2 = s.def.cdr.p.y * m_cellSize + m_cellSize / 2;

//			g2.setStroke(m_thinStroke);
//			g2.setColor(Color.YELLOW);
//			g2.drawLine(x1, y1, x2, y2);

			g2.setStroke(m_lineStroke);
			g2.setColor(s.isAssumed() ? Color.RED : Color.BLACK);
			if (s.getNumber() == 1) {
				g2.drawLine(x1, y1, x2, y2);
			} else if (s.getNumber() == 2) {
				if (x1 == x2) {
					g2.drawLine(x1 - interval, y1, x1 - interval, y2);
					g2.drawLine(x1 + interval, y1, x1 + interval, y2);
				} else if (y1 == y2) {
					g2.drawLine(x1, y1 - interval, x2, y1 - interval);
					g2.drawLine(x1, y1 + interval, x2, y1 + interval);
				} else {
					throw AssertUtil.fail();
				}
			} else if (!s.isFixed() && (s.getPossibilityFlag() & 1) == 0) {
				g2.setColor(Color.MAGENTA);
				g2.drawLine(x1, y1, x2, y2);
			}
		}
		
		// draw islands
		int r = (int) (m_cellSize * 0.52);
		for (int x = 0; x < b.width; x++) {
			for (int y = 0; y < b.height; y++) {
				ShimaDef shima = b.getShima(x, y);
				if (shima != null) {
					int x1 = x * m_cellSize + m_cellSize / 2;
					int y1 = y * m_cellSize + m_cellSize / 2;
					g2.setStroke(m_thinStroke);
					g2.setColor(Color.WHITE);
					g2.fillOval(x1 - r, y1 - r, r * 2, r * 2);
					g2.setColor(Color.BLACK);
					g2.drawOval(x1 - r, y1 - r, r * 2, r * 2);
					drawStringInCell(g2, x, y, String.valueOf(shima.n));
				}
			}
		}

		// draw forbidden marks
		for (HashiState hashiState : b.getHashiStates()) {
			Pnt p1 = hashiState.def.car.p;
			Pnt p2 = hashiState.def.cdr.p;
			Direction d = Direction.quad(p1.vctTo(p2));
			if (hashiState.getNumber() == 0) {
				drawForbiddenMark(g2, p1, d);
				drawForbiddenMark(g2, p2, d.inv());
			}
		}

	}

	private void drawForbiddenMark(Graphics2D g2, Pnt p, Direction d) {
		int x = (int) ((p.x + 0.5 + d.v.dx * 0.5) * m_cellSize);
		int y = (int) ((p.y + 0.5 + d.v.dy * 0.5) * m_cellSize);
		drawCross(g2, x, y, m_dotSize);

	}
}
